package com.renfei.multimediatask.ui.task5;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;

import com.renfei.multimediatask.R;
import com.renfei.multimediatask.util.OpenGlUtils;

import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class TriangleRender implements GLSurfaceView.Renderer {
    private Context context;


    private final String vertexShaderCode =
            "attribute vec4 vPosition;" +
                    "void main() {" +
                    "  gl_Position = vPosition;" +
                    "}";

    private final String fragmentShaderCode =
            "precision mediump float;" +
                    "uniform vec4 vColor;" +
                    "void main() {" +
                    "  gl_FragColor = vColor;" +
                    "}";

    private float vertexData[] = {
            -0.5f, -0.5f,
            0.5f, -0.5f,
            0f, 0.5f
    };

    private FloatBuffer vertexBuffer;
    private int program;//OpenGL程序
    private int position;//顶点坐标


    public TriangleRender(Context context) {
        this.context = context;
        vertexBuffer = OpenGlUtils.createFloatBuffer(vertexData);
    }


    @Override
    public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
        GLES20.glClearColor(0.1f, 0.4f, 0.7f, 1.0f);

        /**
         *
         * OpenGL绘制  是线程相关的，  目前  读取着色器，编译着色器程序，都需要在 onSurfaceCreated 后执行 ，
         * 
         */
        String vertexShder = OpenGlUtils.readShaderFromRawResource(context, R.raw.vertex_shader_triangle);
        String fragmentShader = OpenGlUtils.readShaderFromRawResource(context, R.raw.fragment_shader_triangle);

        program = OpenGlUtils.createProgram(vertexShder, fragmentShader);
        position = GLES20.glGetAttribLocation(program, "position");
    }

    @Override
    public void onSurfaceChanged(GL10 gl10, int width, int height) {
        GLES20.glViewport(0, 0, width, height);
    }

    @Override
    public void onDrawFrame(GL10 gl10) {
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);


        GLES20.glUseProgram(program);

        GLES20.glEnableVertexAttribArray(position);
        GLES20.glVertexAttribPointer(position, 2, GLES20.GL_FLOAT, false, 0, vertexBuffer);

        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3);
    }
}
